﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Step4.Unit8.Modules;

namespace Step4.Unit8.Controllers
{
    // 添加基于声明(Claim)的授权策略
    [Authorize(Policy ="权限管理授权策略")]  // 授权过滤器
    public class UserController : Controller
    {
        /*
            如果你的用户类是你"自定义的"(可以有一些特殊的用户属性)，
            那你想使用Identity做登录、用户管理、授权管理、验证，
            那你"必须继承IdentityUser类"
         */
        private readonly UserManager<IdentityUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        public UserController(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _roleManager = roleManager;
        }

        /// <summary>
        /// 用户列表页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View(_userManager.Users.ToList());
        }


        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(string Id)
        {
            var user = await _userManager.FindByIdAsync(Id);
            var viewModel = new UserEditViewModel();
            viewModel.Id = user.Id;
            viewModel.UserName = user.UserName;
            viewModel.Email = user.Email;
            // 查询用户角色(因)
            viewModel.RoleName = (await _userManager.GetRolesAsync(user)).FirstOrDefault();
            // 角色下拉框数据源
            ViewBag.RoleList = new SelectList(_roleManager.Roles.ToList(),"Name","Name");
            return View(viewModel);
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Delete(string Id)
        {
            var user =await _userManager.FindByIdAsync(Id);
            var result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                return RedirectToAction("Index");
            }
            foreach (var err in result.Errors)
            {
                ModelState.AddModelError("", err.Description);
            }
            return RedirectToAction("Index");
          
        }


        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Submit(UserEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(model.Id);
                user.UserName = model.UserName;
                user.Email = model.Email;
                var result = await _userManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    if (!(await _userManager.IsInRoleAsync(user, model.RoleName)))
                    {
                        // 将角色添加到"用户角色"表中
                        await _userManager.AddToRoleAsync(user, model.RoleName);
                    }
                    return RedirectToAction("Index");
                }

                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError("", err.Description);
                }
            }
            return RedirectToAction("Edit", model); // 这种方式不刷新页面
            
        }
    }
}
